package com.apiauto.http_util;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.CookieStore;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.client.params.ClientPNames;
import org.apache.http.client.params.CookiePolicy;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.cookie.Cookie;
import org.apache.http.entity.FileEntity;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.cookie.BasicClientCookie;
import org.apache.http.util.EntityUtils;

import com.alibaba.fastjson.JSONObject;
import com.apiauto.log.Log;
import com.google.common.base.Strings;

/**
 * PS:请求工具类
 * @author lkk
 *
 */
public class Request{
	//http客户端引用
	public static CloseableHttpClient httpClient;
	
	/**
	 * PS:拼接协议以及访问地址
	 * @param protocol 请求协议
	 * @param url 访问地址
	 * @return 拼接好的地址信息
	 */
	public static String groupHostAndParams(String protocol,String url) {
		url = protocol+"://"+url;
		return url;
	}
	
	/**
	 * PS:拼接主机名,路径以及参数
	 * @param protocol 请求协议
	 * @param url 访问地址
	 * @param params 参数
	 * @return 拼接好的url地址
	 */
	public static String groupHostAndParams(String protocol,String url,String params) {
		//拼接协议及请求地址
		url = protocol+"://"+url;
		if(!Strings.isNullOrEmpty(params)) {
			//将参数转为map
			Map<String,String> paramsMap = (Map<String, String>) JSONObject.parse(params);
			//获取map的key集合
			Set<String> keySet = paramsMap.keySet();
			//计数器
			int i = 1;
			//遍历key值获取value并拼接到地址上
			for(String key:keySet) {
				if(i==1) {
					url = url+"?"+key+"="+paramsMap.get(key);
				}else {
					url = url+"&"+key+"="+paramsMap.get(key);
				}
				i++;
			}
		}
		return url;
	}
	
	/**
	 * PS:发送get请求
	 * @param headers 头部信息
	 * @param protocol 协议版本
	 * @param url 访问地址
	 * @param path 路径
	 * @param params 参数
	 * @return 响应对象
	 */
	public static CloseableHttpResponse sendGetRequest(String requestHeaders,String protocol,String url,String params) {
		//拼接地址
		url = groupHostAndParams(url,params);
		//创建get请求对象
		HttpGet httpGet = new HttpGet(url);
		//将头部信息字符串转为map
		Map<String,String> HeadersMap = (Map<String, String>) JSONObject.parse(requestHeaders);
		//遍历map将头部信息设置到请求中
		for(String key:HeadersMap.keySet()) {
			httpGet.setHeader(key, HeadersMap.get(key));
		}
		// 发送请求获取响应对象
		CloseableHttpResponse httpResponse = null;
		try {
			httpResponse = httpClient.execute(httpGet);
		} catch (IOException e) {
			Log.error("发送get请求失败");
		}
		return httpResponse;
	}
	
	/**
	 * PS:发送post请求
	 * @param headers 头部信息
	 * @param protocol 协议版本
	 * @param url 访问地址
	 * @param path 路径
	 * @param params 参数
	 * @return 响应对象
	 */
	public static CloseableHttpResponse sendPostRequest(String requestHeaders,String protocol, String url,String requestDataType,String params) {
		//拼接URL地址
		url = groupHostAndParams(protocol,url);
		//创建post请求对象
		HttpPost httpPost = new HttpPost(url);
		//将头部信息字符串转为map
		Map<String,String> HeadersMap = (Map<String, String>) JSONObject.parse(requestHeaders);
		//遍历map将头部信息设置到请求中
		for(String key:HeadersMap.keySet()) {
			httpPost.setHeader(key, HeadersMap.get(key));
		}
		CloseableHttpResponse httpResponse = null;
			try {
				//判断请求类型
				if(requestDataType.equals("json")) {
					httpPost.setEntity(new StringEntity(params));
				}else if(requestDataType.equals("file")) {
					//获取指定路径文件
					File file=new File(params);
					//将文件对象转为文件实体对象
					FileEntity fileEntity=new FileEntity(file);
					//发送请求
					httpPost.setEntity(fileEntity);
				}else {
					
				}
				httpResponse = httpClient.execute(httpPost);
			} catch (Exception e) {
				Log.error("发送POST请求失败");
			}
		return httpResponse;
	}
	
	/**
	 * PS:发送put请求
	 * @param headers 头部信息
	 * @param protocol 协议版本
	 * @param url 访问地址
	 * @param path 路径
	 * @param params 参数
	 * @return 响应对象
	 */
	public static CloseableHttpResponse sendPutRequest(String requestHeaders,String protocol,String url,String params) {
		//拼接URL地址
		url = groupHostAndParams(protocol,url);
		//创建put请求对象
		HttpPut httpPut = new HttpPut(url);
		//将头部信息字符串转为map
		Map<String,String> HeadersMap = (Map<String, String>) JSONObject.parse(requestHeaders);
		//遍历map将头部信息设置到请求中
		for(String key:HeadersMap.keySet()) {
			httpPut.setHeader(key, HeadersMap.get(key));
		}
		CloseableHttpResponse httpResponse = null;
		try {
			//设置主体信息
			httpPut.setEntity(new StringEntity(params));
			httpResponse = httpClient.execute(httpPut);
		} catch (Exception e) {
			Log.error("发送PUT请求失败");
		}
		return httpResponse;
	}
	/**
	 * PS:发送delete请求
	 * @param headers 头部信息
	 * @param protocol 协议版本
	 * @param url 访问地址
	 * @param path 路径
	 * @param params 参数
	 * @return 响应对象
	 */
	public static CloseableHttpResponse sendDeleteRequest(String requestHeaders, String protocol,String url,String params) {
		url = groupHostAndParams(url,params);
		// 创建Delete请求对象
		HttpDelete httpDelete = new HttpDelete(url);
		//将头部信息字符串转为map
		Map<String,String> HeadersMap = (Map<String, String>) JSONObject.parse(requestHeaders);
		//遍历map将头部信息设置到请求中
		for(String key:HeadersMap.keySet()) {
			httpDelete.setHeader(key, HeadersMap.get(key));
		}
		// 发送请求获取响应对象
		CloseableHttpResponse httpResponse = null;
		try {
			httpResponse = httpClient.execute(httpDelete);
		} catch (IOException e) {
			Log.error("发送DELETE请求失败");
		}
		return httpResponse;
	}
	
	/**
	 * PS:发送请求服务
	 * @param method 请求方式
	 * @param headers 头部信息
	 * @param protocol 协议版本
	 * @param url 访问地址
	 * @param params 参数
	 * @return 响应对象
	 */
	public static CloseableHttpResponse doServer(String method,String requestHeaders,String protocol,String url,String requestDataType,String params) {
		//获取http客户端对象
		httpClient = HttpClients.createDefault();
		//cookie保存对象
		//CookieStore cookieStore = new BasicCookieStore();
		//发送对象设置cookie保存机制
		//httpClient = HttpClients.custom().setDefaultCookieStore(cookieStore).build();
		//根据请求方式选择方法发送请求
		if("GET".equals(method.toUpperCase())){
			return sendGetRequest(requestHeaders,protocol,url, params);
		}else if("POST".equals(method.toUpperCase())){
			return sendPostRequest(requestHeaders,protocol,url,requestDataType, params);
		}else if("PUT".equals(method.toUpperCase())){
			return sendPutRequest(requestHeaders,protocol,url, params);
		}else {
			return sendDeleteRequest(requestHeaders,protocol,url, params);
		}
	}
	
}
